﻿//-----------------------------------------------------------------------------
// Copyright (c) BaFang Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace BaFangSpider
{

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Timers;
    using LumiSoft.Net.Mail;

    /// <summary>
    /// Summary description for MonitorService
    /// </summary>
    public class MonitorService
    {
        protected Timer checkServiceTimer = new Timer();
        protected Timer checkListenerTimer = new Timer();

        protected string mailAddress = null;

        public MonitorService()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        protected void CheckServiceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                CheckWebSites();
            }
            catch(Exception ex)
            {
                Logger.GetLogger().Write("Exception!!!!!" + ex.Message);
            }
        }

        protected virtual void CheckWebSites()
        {
 
        }

        protected virtual void UpdateListenserRegisteredService(string interest, string content)
        {
        }

        protected virtual void CheckMailAndRemoveListeners(Mail_Message message)
        { 
        }

        public void CheckAndUpdateListeners()
        {
            Logger logger = Logger.GetLogger();
            logger.Write(DateTime.Now.ToString() + ":Start Check and Add listerners in " + this.mailAddress);
            lock (this.mailAddress)
            {
                Debug.Assert(this.mailAddress != null);
                IList<Mail_Message> mails = ReceiveMail.Receive(this.mailAddress);
                logger.Write(DateTime.Now.ToString() + ": Mails count: " + mails.Count);
                foreach (Mail_Message message in mails)
                {
                    string title = message.Subject.Trim();
                    if(title.StartsWith("Update:"))
                    {
                        string interest = title.Substring(7);
                        string code = message.BodyText.Trim();
                        this.UpdateListenserRegisteredService(interest, code);
                    }
                }
            }
            logger.Write(DateTime.Now.ToString() + ":End Check and Add listerners:");
        }

        protected string GetKeywordInMailTitle(string s, out int next)
        {
            next = -1;
            if (string.IsNullOrEmpty(s))
            {
                return null;
            }
            int index1 = s.IndexOf("<");
            int index2 = s.IndexOf(">", index1 + 1);
            if (index1 > 0 && index2 > index1)
            {
                next = index2;
                return s.Substring(index1 + 1, index2 - index1 - 1);
            }
            return null;
        }

        public virtual void Start()
        {
            checkServiceTimer.AutoReset = true;
            checkServiceTimer.Enabled = true;
            checkServiceTimer.Interval = 30000; // 0.5 minutes.
            checkServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckServiceTimer_Elapsed);

            checkListenerTimer.AutoReset = true;
            checkListenerTimer.Enabled = true;
            checkListenerTimer.Interval = 15000;  // check mail frequency.
            checkListenerTimer.Elapsed += new ElapsedEventHandler(checkListenerTimer_Elapsed);
        }

        void checkListenerTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                this.CheckAndUpdateListeners();
            }
            catch (Exception ex)
            {
                // to Make the spider robust, we just catch the exception and log it.
                Logger.GetLogger().Write("Exception!!!!!" + ex.Message + ":"　+ this.mailAddress);
            }
        }

        public virtual void Stop()
        {
            checkServiceTimer.Stop();
            checkServiceTimer.Dispose();

            this.checkListenerTimer.Stop();
            this.checkListenerTimer.Dispose();
        }
    }
}